package cn.fastoo.web.backstage.web.controller.system;

import cn.fastoo.common.dao.system.RoleDao;
import cn.fastoo.common.dao.system.UserBaseInfoDao;
import cn.fastoo.common.entity.product.ProductBrand;
import cn.fastoo.common.entity.system.Role;
import cn.fastoo.common.entity.system.UserBaseInfo;
import cn.fastoo.common.sampleframe.dto.JsonResult;
import cn.fastoo.common.sampleframe.search.QuerySearch;
import cn.fastoo.common.sampleframe.search.Search;
import cn.fastoo.common.sampleframe.springside.Servlets;
import cn.fastoo.common.utils.ResponseTypeOutUtils;
import cn.fastoo.web.backstage.param.DataGridParam;
import cn.fastoo.web.backstage.utils.DataGridUtils;
import cn.fastoo.web.backstage.utils.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 用户页面 控制器.
 */
@Controller
@RequestMapping("/system/user")
public class SystemUserController {
	private static Logger logger = LoggerFactory.getLogger(SystemUserController.class);

	@Autowired
	private UserBaseInfoDao userBaseInfoDao;
	//private userBaseInfoDao userBaseInfoDao;
	@Autowired
	private RoleDao roleService;

	@RequiresPermissions(value = { "system:product:read" })
	@RequestMapping
	public String index(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		return "system/user/index";
	}

	@RequestMapping("/manager")
	@ResponseBody
	public String manager(@ModelAttribute UserBaseInfo newData, QuerySearch querySearch, String op) {
		Search search = querySearch.getSearch();
		if(org.apache.commons.lang.StringUtils.isNotBlank(op)){
			if("add".equals(op)){
				userBaseInfoDao.insert(newData);
				//logger.info(loginUser, SystemLog.TYPE_AUTH_ROLE_ADD,String.format("用户角色[%s]",authRole.getRoleName()));
			}else {
				UserBaseInfo oldData = userBaseInfoDao.findById(newData.getId());
				if(oldData==null){
					return JsonResult.success("错误参数,请检查");
				}
				if("save".equals(op)){

					oldData.setName(newData.getName());
					oldData.setLoginName(newData.getLoginName());
					oldData.setPassword(newData.getPassword());

					userBaseInfoDao.update(oldData);
				}else if("del".equals(op)){
					userBaseInfoDao.delete(oldData);
				}
			}
			return JsonResult.success("操作成功");
		}
		return JsonResult.querySearchSuccess(userBaseInfoDao.find(search),querySearch);
	}

	@RequestMapping("base")
	public String base() {
		return "system/base";
	}


	@RequestMapping("changePwd")
	@ResponseBody
	public String changePwd(@RequestParam String oldPwd,@RequestParam String newPwd) {
		UserBaseInfo userBaseInfo = userBaseInfoDao.findByLoginName(ShiroUtils.getLoginName());
		if(!userBaseInfo.getPassword().equals(oldPwd)){
			return JsonResult.error("原密码错误");
		}
		userBaseInfo.setPassword(newPwd);
		userBaseInfoDao.update(userBaseInfo);
		return JsonResult.success("修改成功");
	}


	/**
	 * 获取用户分页list数据，并转换为前端grid插件所需数据格式
	 * 
	 * @param dataGridParam
	 * @param request
	 * @param response
	 */
	@RequiresPermissions(value = { "system:rsync:read" })
	@RequestMapping("/list")
	public void list(@ModelAttribute DataGridParam dataGridParam, HttpServletRequest request, HttpServletResponse response) {
		try {
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
			Sort sort = new Sort(Direction.valueOf(dataGridParam.getOrder()), dataGridParam.getSort());
			PageRequest pageRequest = new PageRequest(dataGridParam.getPage(), dataGridParam.getRows(), sort);
			Page<UserBaseInfo> page = userBaseInfoDao.findPage(new Search().addPageRequest(pageRequest).addSearchFilter(searchParams));
			ResponseTypeOutUtils.renderJson(response, DataGridUtils.PageToJson(page));
		} catch (Exception e) {
			//logger.error("[{}]用户分页List获取失败：{}", SystemUtils.getCurrentUserName(), dataGridParam, e);
		}
	}

	/**
	 * 储存用户 新增和修改均使用同一方法
	 * 
	 * @param permission
	 * @param request
	 * @param response
	 */
	@RequiresPermissions(value = { "system:rsync:edit" })
	@RequestMapping("/save")
	public void save(@ModelAttribute UserBaseInfo user, HttpServletRequest request, HttpServletResponse response) {
		try {
			if(StringUtils.isBlank(user.getRoleIds())){
				user.setRoleIds("");
			}
			if (user.getId() != null) {
				UserBaseInfo oldUser = userBaseInfoDao.findById(user.getId());
				oldUser.setPassword(user.getPassword());
				oldUser.setLoginName(user.getLoginName());
				oldUser.setName(user.getName());
				oldUser.setRoleIds(user.getRoleIds());
				userBaseInfoDao.update(oldUser);
			}else{
				userBaseInfoDao.insert(user);
			}
			ResponseTypeOutUtils.renderJsonSuccess(response, "用户储存失败");
		} catch (Exception e) {
			ResponseTypeOutUtils.renderJsonError(response, "用户储存失败");
		}
	}

	/**
	 * 删除用户 注意请求参数名称为"ids[]"
	 * 
	 * @param ids
	 * @param request
	 * @param response
	 */
	@RequiresPermissions(value = { "system:rsync:delete" })
	@RequestMapping("/delete")
	public void delete(@RequestParam("ids[]") Long[] ids, HttpServletRequest request, HttpServletResponse response) {
		try {
			List<UserBaseInfo> list = new ArrayList<UserBaseInfo>();
			for (Long id : ids) {
				UserBaseInfo user = userBaseInfoDao.findById(id);
				if(user!=null){
					userBaseInfoDao.delete(user);
				}
			}
			ResponseTypeOutUtils.renderJsonSuccess(response, "用户删除成功");
		} catch (Exception e) {
			ResponseTypeOutUtils.renderJsonError(response, "用户删除失败");
		}
	}

	/**
	 * 获取用户角色
	 * 
	 * @param roleId
	 * @param request
	 * @param response
	 */
	@RequiresPermissions(value = { "system:rsync:read" })
	@RequestMapping("/getUserRole")
	public void getUserRole(HttpServletRequest request, HttpServletResponse response) {
		String userId = request.getParameter("userId");
		try {
			List<Role> list = new ArrayList<Role>();
			if (StringUtils.isNotBlank(userId)) {
				UserBaseInfo user = userBaseInfoDao.findById(Long.parseLong(userId));
				if(StringUtils.isNotBlank(user.getRoleIds())){
					list = roleService.find(new Search().addSearchFilter("IN_id",user.getRoleIds()));
				}
			}
			String json = DataGridUtils.ListToJson(list);
			ResponseTypeOutUtils.renderJson(response, json);
		} catch (Exception e) {
		}
	}

	/**
	 * 获取用户可选角色page(包含已经选择的)
	 * 
	 * @param roleId
	 * @param request
	 * @param response
	 */
	@RequiresPermissions(value = { "system:rsync:read" })
	@RequestMapping("/getChooseRoles")
	public void getChooseRoles(@ModelAttribute DataGridParam dataGridParam, HttpServletRequest request, HttpServletResponse response) {
		try {
			Sort sort = new Sort(Direction.valueOf(dataGridParam.getOrder()), dataGridParam.getSort());
			PageRequest pageRequest = new PageRequest(dataGridParam.getPage(), dataGridParam.getRows(), sort);
			Page<Role> page = roleService.getUserChooseRolePage(pageRequest);
			ResponseTypeOutUtils.renderJson(response, DataGridUtils.PageToJson(page));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
